package cqrtplm.listener;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.hustcad.plm.pdm.workflow.annotion.CustomListener;
import com.hustcad.plm.pdm.workflow.annotion.CustomListenerField;
import com.hustcad.plm.pdm.workflow.model.constant.ProcessConstant;
import com.ty.basic.session.RequestContext;
import cqrtplm.service.RTChangeNoticeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.flowable.engine.impl.el.FixedValue;

import java.math.BigInteger;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : pieStar
 * @create 2025/7/22 21:54
 */
@Slf4j
@CustomListener(category = "润通", description = "将对象上一个大版本状态设置为失效")
public class RTSetSecVersionStatusListener implements ExecutionListener {
    @CustomListenerField(description = "目标生命周期状态", defaultValue = "", required = true)
    private FixedValue parma;

    @Override
    public void notify(DelegateExecution execution) {
        long start = System.currentTimeMillis();
        String workFlowContainerId = execution.getProcessInstanceBusinessKey();
        log.info("----------润通----将对象上一个大版本状态设置为失效------开始------workFlowContainerId:{}----->>>", workFlowContainerId);
        if (StringUtils.isBlank(workFlowContainerId)) {
            workFlowContainerId = execution.getVariable(ProcessConstant.WORK_FLOW_CONTAINER_ID).toString();
        }
        String targetLifeCycleStateKey = "";
        if (parma != null) {
            targetLifeCycleStateKey = parma.getExpressionText();
        }
        String finalWorkFlowContainerId = workFlowContainerId;
        Map<String, Object> requestContext = RequestContext.currentContext();
        RTChangeNoticeService changeNoticeService = SpringUtil.getBean(RTChangeNoticeService.class);
        try {
            changeNoticeService.setSecVersionStatus(new BigInteger(finalWorkFlowContainerId), targetLifeCycleStateKey);
        } catch (Exception e) {
            log.info("将对象上一个大版本状态设置为失效");
            log.error(ExceptionUtil.getMessage(e));
            log.error(ExceptionUtil.stacktraceToString(e, 100000));
        }
        log.info("----------润通----将对象上一个大版本状态设置为失效,耗时：{}---->>>", System.currentTimeMillis() - start);
    }
}
